package com.naiterui.ehp.bs.agent.controller;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.constants.CommonConstant;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.security.HeaderConstant;
import com.naiterui.ehp.bp.utils.biz.VersionUtil;
import com.naiterui.ehp.bs.agent.exception.ExceptionCodes;
import com.naiterui.ehp.bs.agent.vo.VersionResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yiren
 * @since 2022/3/2
 */
@Slf4j
@Api(tags = {SwaggerTag.AGENT + "版本相关接口"})
@AllArgsConstructor
@RestController
@RequestMapping("version")
public class VersionController {
    private Map<String, VersionResultVo> versionResult = new HashMap<>();
    private Map<String, Integer> forceVersionList = new HashMap<>();
    private static final String VERSION_1_0_0 = "1.0.0";

    @GetMapping("check")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "version", value = "当前版本号", dataType = "string", paramType = "query", required = true),
            @ApiImplicitParam(name = "platform", value = "iphone,android", dataType = "string", paramType = "query"),
    })
    public VersionResultVo checkVersion(String version, String platform, HttpServletRequest request) throws BusinessException {

        // 优先使用header中的值
        String hVersion = request.getHeader(HeaderConstant.HEADER_VERSION);
        String hPpaltform = request.getHeader(HeaderConstant.HEADER_PLATFORM);
        log.info("客户端header版本号为:version=" + hVersion + ",paltform=" + hPpaltform);
        // 返回vo
        VersionResultVo vo = new VersionResultVo();
        if (StringUtils.isNotEmpty(hVersion) && StringUtils.isNotEmpty(hPpaltform) ) {
            if (hPpaltform.equals(HeaderConstant.HEADER_PLATFORM_ANDROID_PHONE + "")) {
                vo = this.getVersionVo("0", hVersion);
            } else if (hPpaltform.equals(HeaderConstant.HEADER_PLATFORM_IOS_PHONE + "")) {
                vo = this.getVersionVo("1", hVersion);
            }
            return vo;
        }
        log.info("客户端请求版本号为:version=" + version + ",platform=" + platform);
        if (StringUtils.isBlank(platform)) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        if ("iphone".equals(platform.toLowerCase()) || "2".equals(platform.toLowerCase())) {
            vo = this.getVersionVo("1", version);
        } else if ("android".equals(platform.toLowerCase()) || "1".equals(platform.toLowerCase())) {
            vo = this.getVersionVo("0", version);
        }

        if (vo == null) {
            vo = new VersionResultVo();
            vo.setResult(0);
            vo.setPrompt("你已经是最新版本了");
            vo.setUrl("");
            vo.setLastVerNum("1.0.0");
            vo.setLastVerSize("6M");
        }

        return vo;
    }

    @PostMapping("update")
    public void updateVersion(String appPlat, String lastVerNum, String lastVerSize, String result, String forceVersion, String content,
                     String url) throws BusinessException {

        log.info("输入平台:" + appPlat + ",最新版本号:" + lastVerNum + ",最新版本大小:" + lastVerSize + ",被更新版本号:" + forceVersion + ",更新提示语:" + content
                + ",更新跳转地址:" + url);
        // 输入配置参数为空时，直接提示参数错误
        if (StringUtils.isBlank(appPlat) || StringUtils.isBlank(lastVerNum) || StringUtils.isBlank(lastVerSize) || StringUtils.isBlank(result)
                || StringUtils.isBlank(content) || StringUtils.isBlank(url)) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }

        if (lastVerNum.split("\\.").length != 3 || (StringUtils.isNotBlank(forceVersion) && forceVersion.split("\\.").length != 3)) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }

        VersionResultVo vo = new VersionResultVo();
        vo.setLastVerNum(lastVerNum);
        if (!"".equals(lastVerSize)) {
            lastVerSize = lastVerSize.trim().toLowerCase().endsWith("M") ? lastVerSize : lastVerSize + "M";
        }
        vo.setLastVerSize(lastVerSize);
        vo.setResult(Integer.parseInt(result));
        vo.setPrompt(content);
        vo.setUrl(url);
        String versionkey = this.getRedisVersionCheckKey(appPlat);
        // 数据存放在redis中永久有效
        RedisUtil.valueOps().set(versionkey, vo);

        // 数据存放在redis中永久有效
        String forcekey = this.getRedisForceVersionKey(appPlat);
        if ("2".equals(result)) {
            RedisUtil.valueOps().set(forcekey, lastVerNum);
        } else if ("1".equals(result) && forceVersion != null && !"".equals(forceVersion)) {
            RedisUtil.valueOps().set(forcekey, forceVersion);
        }
        this.versionResult.clear();
        this.forceVersionList.clear();
    }

    public String getRedisVersionCheckKey(String appPlat) {
        return CommonConstant.REDIS_PRE_AGENT + "version_check_" + appPlat;
    }

    public String getRedisForceVersionKey(String appPlat) {
        return CommonConstant.REDIS_PRE_AGENT + "ver_force_" + appPlat;
    }

    private VersionResultVo getVersionVo(String appPlat, String version) {
        // 传递的版本
        String versionkey = this.getRedisVersionCheckKey(appPlat);

        VersionResultVo vo = (VersionResultVo) RedisUtil.valueOps().getObject(versionkey);

        // 升级最新版本
        String checkVersion = VERSION_1_0_0;
        // 升级等级 0-最新版本，1-建议升级，2-强制升级
        Integer checkResult = 0;
        if (vo != null) {
            checkVersion = vo.getLastVerNum();
            checkResult = vo.getResult();
        }

        // 如果当前升级等级为强制升级，则所有系统设置版本(checkVersion)大于客户版本(versionInt)则提示需要强制升级
        if (checkResult == 2 && VersionUtil.compareVersion(checkVersion, version) > 0) {
            return vo;
        }
        // 如果当前升级等级为建议升级，则需要判断是否有特底版本需要将升级等级提升至强制升级
        String forcekey = this.getRedisForceVersionKey(appPlat);
        String forceVersionStr = RedisUtil.valueOps().getString(forcekey);
        if (forceVersionStr == null) {
            forceVersionStr = VERSION_1_0_0;
        }

        // 如果当前升级为建议升级，且登记提升版本(forceVersion)大于客户版本(versionInt)，则返回强制升级
        if (checkResult == 1 && VersionUtil.compareVersion(forceVersionStr, version) > 0) {
            // 调整升级升级至强制升级
            VersionResultVo temp = new VersionResultVo();
            temp.setResult(2);
            temp.setPrompt(vo.getPrompt());
            temp.setUrl(vo.getUrl());
            temp.setLastVerNum(vo.getLastVerNum());
            temp.setLastVerSize(vo.getLastVerSize());
            return temp;
        }
        // 如果传递的版本小于升级版本，则强制升级。
        if (VersionUtil.compareVersion(checkVersion, version) <= 0) {
            // 不需要升级
            vo = new VersionResultVo();
            vo.setResult(0);
            vo.setPrompt("你已经是最新版本了");
            vo.setUrl("http://www.baidu.com");
            vo.setLastVerNum("1.3.0");
            vo.setLastVerSize("6M");
        }
        return vo;
    }
}
